using UnityEngine;

public class PlayerStats : MonoBehaviour
{
    [Header("主要属性")]
    public float maxHealth = 100f;
    public float currentHealth;
    public float defense = 1f;
    public float moveSpeed = 3.5f; // 我们之前调好的速度
    public float pickupRange = 50f; 

    [Header("伤害与冷却")]
    public float damageBonus = 0f;
    public float cooldownReduction = 0f;

    [Header("其他")]
    public float luck = 0f;

    [Header("等级与经验")]
    public int level = 1;
    public int currentExp = 0;
    public int requiredExp;

    void Awake()
    {
        currentHealth = maxHealth;
        CalculateRequiredExp();
    }

    void Start()
    {
        GetComponent<PlayerMovement>().moveSpeed = this.moveSpeed;
    }

    void Update()
    {
        // 临时测试：按 K 键给自己加经验
        if (Input.GetKeyDown(KeyCode.K))
        {
            AddExperience(10);
        }
        
        // 临时测试：按空格恢复时间
        if (Input.GetKeyDown(KeyCode.Space) && Time.timeScale == 0f)
        {
            Time.timeScale = 1f;
        }
    }
    
    // 计算当前等级升到下一级所需的经验
    void CalculateRequiredExp()
    {
        requiredExp = Mathf.FloorToInt(20 * Mathf.Pow(level, 1.5f));
        Debug.Log("下一级需要经验: " + requiredExp);
    }

    // 增加经验值
    public void AddExperience(int amount)
    {
        currentExp += amount;
        Debug.Log("获得经验: " + amount + ", 当前经验: " + currentExp + "/" + requiredExp);

        while (currentExp >= requiredExp)
        {
            currentExp -= requiredExp;
            level++;
            CalculateRequiredExp();
            LevelUp();
        }
    }
    
    // 升级时调用的方法
    void LevelUp()
    {
        Debug.Log("升级了！当前等级: " + level);
        Time.timeScale = 0f; // 时间停止！
    }

    // 新增：处理受伤的函数
    public void TakeDamage(float damage)
    {
        // 根据GDD，计算实际伤害 = 怪物伤害 - 玩家防御
        float actualDamage = damage - defense;

        // 如果防御力更高，则不受伤害
        if (actualDamage > 0)
        {
            currentHealth -= actualDamage;
            Debug.Log("玩家受到 " + actualDamage + " 点伤害, 剩余生命: " + currentHealth);

            // 检查玩家是否死亡
            if (currentHealth <= 0)
            {
                currentHealth = 0; // 避免血量显示为负数
                Die();
            }
        }
        else
        {
            Debug.Log("伤害被防御格挡！");
        }
    }
    
    // 新增：处理死亡的函数
    private void Die()
    {
        Debug.Log("玩家已死亡！游戏结束！");
        // 暂停游戏，为弹出失败界面做准备
        Time.timeScale = 0f; 
    }
}